package com.ruoyi.web.controller.test5;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.test2.domain.Materialtable;
import com.ruoyi.test2.service.IMaterialtableService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.test5.domain.Resourcerequest;
import com.ruoyi.test5.service.IResourcerequestService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 资源请求Controller
 * 
 * @author 22082112
 * @date 2025-07-10
 */
@RestController
@RequestMapping("/resourcerequest/resourcerequest")
public class ResourcerequestController extends BaseController
{
    @Autowired
    private IResourcerequestService resourcerequestService;

    @Autowired
    private IMaterialtableService materialService; // 物资 Service


    /**
     * 查询资源请求列表
     */
    @PreAuthorize("@ss.hasPermi('resourcerequest:resourcerequest:list')")
    @GetMapping("/list")
    public TableDataInfo list(Resourcerequest resourcerequest)
    {
        startPage();
        List<Resourcerequest> list = resourcerequestService.selectResourcerequestList(resourcerequest);
        return getDataTable(list);
    }

    /**
     * 导出资源请求列表
     */
    @PreAuthorize("@ss.hasPermi('resourcerequest:resourcerequest:export')")
    @Log(title = "资源请求", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Resourcerequest resourcerequest)
    {
        List<Resourcerequest> list = resourcerequestService.selectResourcerequestList(resourcerequest);
        ExcelUtil<Resourcerequest> util = new ExcelUtil<Resourcerequest>(Resourcerequest.class);
        util.exportExcel(response, list, "资源请求数据");
    }

    /**
     * 获取资源请求详细信息
     */
    @PreAuthorize("@ss.hasPermi('resourcerequest:resourcerequest:query')")
    @GetMapping(value = "/{requestId}")
    public AjaxResult getInfo(@PathVariable("requestId") String requestId)
    {
        return success(resourcerequestService.selectResourcerequestByRequestId(requestId));
    }

    // 库存校验逻辑
    private boolean checkMaterialStock(Long materialId, Long quantity) {
        if (materialId == null) {
            return true;
        }
        Materialtable material = materialService.selectMaterialtableBySupplyid(materialId);
        if (material == null) {
            return false;
        }
        Integer currentStock;
        try {
            currentStock = Integer.parseInt(material.getCurrent());
        } catch (NumberFormatException e) {
            return false;
        }
        return quantity == null || quantity.intValue() <= currentStock;
    }



    /**
     * 新增资源请求
     */
    @PreAuthorize("@ss.hasPermi('resourcerequest:resourcerequest:add')")
    @Log(title = "资源请求", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Resourcerequest resourcerequest)
    {
        // 校验物资库存
        if (!checkMaterialStock(resourcerequest.getMaterialId(), resourcerequest.getMaterialQuantity())) {
            return AjaxResult.error("请求数量超过物资当前库存");
        }
        return toAjax(resourcerequestService.insertResourcerequest(resourcerequest));
    }

    /**
     * 修改资源请求
     */
    @PreAuthorize("@ss.hasPermi('resourcerequest:resourcerequest:edit')")
    @Log(title = "资源请求", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Resourcerequest resourcerequest)
    {
        if (!checkMaterialStock(resourcerequest.getMaterialId(), resourcerequest.getMaterialQuantity())) {
            return AjaxResult.error("请求数量超过物资当前库存");
        }
        return toAjax(resourcerequestService.updateResourcerequest(resourcerequest));
    }


    //resourcerequest:resourcerequest:auth
    @PreAuthorize("@ss.hasPermi('resourcerequest:resourcerequest:auth')")
    @Log(title = "审批物资请求", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/auth")
    public AjaxResult auth(@RequestBody Resourcerequest resourcerequest) {
        // 1. 校验 statusId 非空
        Long statusId = resourcerequest.getStatusId();
        // 2. 后续逻辑（仅当 statusId 非空时执行）
        int ret = 0;
        if (!checkMaterialStock(resourcerequest.getMaterialId(), resourcerequest.getMaterialQuantity())) {
            return AjaxResult.error("库存不足，审批失败");
        }
        // 3. 仅当状态为“已批准”（2L）时扣减库存
        if (statusId == 2L && resourcerequest.getMaterialId() != null) {  // 此时 statusId 已非空，可安全使用
            Materialtable material = materialService.selectMaterialtableBySupplyid(resourcerequest.getMaterialId());
            try {
                Integer currentStock = Integer.parseInt(material.getCurrent());
                if (resourcerequest.getMaterialQuantity() != null) {
                    currentStock -= resourcerequest.getMaterialQuantity().intValue();
                }
                material.setCurrent(String.valueOf(currentStock));
                ret = materialService.updateMaterialtable(material);
            } catch (NumberFormatException e) {
                return AjaxResult.error("库存格式错误，扣减失败");
            }
        }
        // 4. 更新资源请求状态（确保无论是否扣减库存，状态都能保存）
        resourcerequestService.updateResourcerequest(resourcerequest);
        return toAjax(ret > 0 ? ret : 1);  // 即使未扣减库存，也返回成功（状态已更新）
    }


    /**
     * 删除资源请求
     */
    @PreAuthorize("@ss.hasPermi('resourcerequest:resourcerequest:remove')")
    @Log(title = "资源请求", businessType = BusinessType.DELETE)
	@DeleteMapping("/{requestIds}")
    public AjaxResult remove(@PathVariable String[] requestIds)
    {
        return toAjax(resourcerequestService.deleteResourcerequestByRequestIds(requestIds));
    }
}
